package com.neusoft.elmboot.service.impl;

import java.util.List;

import com.neusoft.elmboot.dto.CartDTO;
import com.neusoft.elmboot.mapper.FoodMapper;
import com.neusoft.elmboot.po.Food;
import com.neusoft.elmboot.service.ex.*;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.elmboot.mapper.CartMapper;
import com.neusoft.elmboot.po.Cart;
import com.neusoft.elmboot.service.CartService;

@Service
public class CartServiceImpl implements CartService{
	
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private FoodMapper foodMapper;

	@Override
	public List<Cart> listCart(Cart cart) {
		List<Cart> list = cartMapper.listCart(cart);
		if(list != null && !list.isEmpty()){
			return list;
		}
		else{
			throw new DataNotFoundException("购物车为空，获取购物车列表失败!");
		}
	}
	
	@Override
	public int saveCart(Cart cart) {
			//检查库存数量
			Food food = foodMapper.getFoodById(cart.getFoodId());
			if(food == null) {
				throw new DataNotFoundException("商品不存在，添加失败！");
			}
			if(food.getCount() < 1) {
				//检查库存
				//此处默认初次在购物车中添加食物的数量为1
				throw new NotEnoughException("商品库存不足，添加商品失败！");
			}
			int result = cartMapper.saveCart(cart);
			if(result <= 0) {
				throw new InsertException("添加购物车食物失败！");
			}
			return result;

	}

	@Override
	public int updateCart(Cart cart) {

		//更新购物车中的食物数量 增加或者减少
		//这里的逻辑应该是，在购物车中增加或者减少食物数量 这是不需要进行判断食物库存的 而是应该在创建订单时进行判断，这里只是更新购物车中的食物数量

		//首先获取当前购物车中的某种食物数量
		//Cart currentCart = cartMapper.getCartByUserIdAndFoodIdAndBusinessId(cart);
		//int currentQuantity = currentCart.getQuantity();
		////这里的新传入的quantity只能传入1或者-1
		//int num = cart.getQuantity();
		//	if(num == 1) {
		//		cart.setQuantity(currentQuantity + 1);
		//		return cartMapper.updateCart(cart);
		//	}
			//else if(num == -1) {
			//	cart.setQuantity(currentQuantity - 1);
			//	if(cart.getQuantity() < 1) {
					//购物车中食物数量小于1时，删除购物车中的食物
			//		return cartMapper.removeCart(cart);
			//	}
			int result = cartMapper.updateCart(cart);
			if(result <= 0) {
				throw new UpdateException("更新购物车食物数量失败！");
			}
				return result;
	}
	
	@Override
	public int removeCart(Cart cart) {
		int result = cartMapper.removeCart(cart);
		if(result <= 0) {
			throw new DeleteException("删除购物车食物失败！");
		}
		return result;
	}

	@Override
	public int clearCart(CartDTO cartDTO) {
		int result = cartMapper.clearCart(cartDTO);
		if(result <= 0) {
			throw new DeleteException("清空购物车失败！");
		}
		return result;
	}
}
